<template>
  <div class="accountList">
    <div class="searchBox">
      <el-form :model="searchForm" ref="searchFormRef">
        <el-row>
          <el-form-item prop="companyName">
            <div class="item">
              <span v-html="'企业名称'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.companyName"
                placeholder="请输入企业名称"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="name">
            <div class="item">
              <span v-html="'姓名'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.name"
                placeholder="请输入姓名"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="phone">
            <div class="item">
              <span v-html="'手机号'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.phone"
                placeholder="请输入手机号"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="audit">
            <div class="item">
              <span v-html="'审核状态'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.audit"
                placeholder="请选择审核状态"
                size="mini"
              >
                <el-option
                  v-for="item in auditOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="status">
            <div class="item">
              <span v-html="'状态'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.status"
                placeholder="请选择状态"
                size="mini"
              >
                <el-option
                  v-for="item in stautsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="istrial">
            <div class="item">
              <span v-html="'是否试用'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.istrial"
                placeholder="请选择是否试用"
                size="mini"
              >
                <el-option
                  v-for="item in istrialOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="currentPlanId">
            <div class="item">
              <span v-html="'套餐'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.currentPlanId"
                placeholder="请选择套餐"
                size="mini"
              >
                <el-option
                  v-for="item in plans"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="businessAdminId">
            <div class="item">
              <span v-html="'专属业务员'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.businessAdminId"
                placeholder="请选择专属业务员"
                size="mini"
              >
                <el-option
                  v-for="item in salesmansList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="searchClick"
              icon="el-icon-search"
              type="primary"
              size="mini"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
              >重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="custom-style">
      <el-popover placement="bottom-start" width="200" trigger="click">
        <el-checkbox-group v-model="checkedCities">
          <el-checkbox
            @change="saveCustom"
            v-for="(item, index) in cities"
            :label="item"
            :key="index"
            style="display: block; padding-top: 10px; margin-left: 27px"
            >{{ item }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="primary" size="mini" slot="reference">自定义列表</el-button>
      </el-popover>
    </div>
    <div class="tableBox" ref="tableBoxRef">
      <el-table
        v-loading="tableLoading"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        border
        :data="tableData"
        style="width: 100%"
         :height="570"
      >
        <el-table-column
          v-if="checkedCities.includes('套餐')"
          prop="currentPlanName"
          align="center"
          label="套餐"
        >
          <template slot-scope="scope">
            <div
              :style="{
                color:
                  scope.row.currentPlanId == 2
                    ? '#169bd5'
                    : scope.row.currentPlanId == 3
                    ? '#b8741a'
                    : '',
              }"
            >
              {{ scope.row.currentPlanName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('有效期')"
          align="center"
          label="有效期"
          width="200"
        >
          <template slot-scope="scope" >
            <div>
              <div  v-if="scope.row.trialPlanName">
                {{ scope.row.trialPlanName }}试用中
              </div>
              <div v-if='scope.row.startTime!=null'>
                {{ scope.row.startTime  }}至{{
                  scope.row.endTime 
                }}
              </div>
              <div v-else>-</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('企业名称')"
          prop="companyName"
          align="center"
          label="企业名称"
          width="150"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('姓名')"
          prop="name"
          align="center"
          label="姓名"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('手机号')"
          prop="phone"
          align="center"
          label="手机号"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('邮箱')"
          prop="email"
          align="center"
          label="邮箱"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('职位')"
          prop="position"
          align="center"
          label="职位"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('注册时间')"
          prop="createTime"
          align="center"
          label="注册时间"
        >
          <template slot-scope="scope">{{
            scope.row.createTime | formatDate
          }}</template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('注册来源')"
          prop="channel"
          align="center"
          label="注册来源"
        >
          <template slot-scope="scope">
            {{ channelFormatter[scope.row.channel] }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('审核状态')"
          prop="audit"
          align="center"
          label="审核状态"
        >
          <template slot-scope="scope">
            {{ auditFormatter[scope.row.audit] }}
          </template>
        </el-table-column>

        <el-table-column
          v-if="checkedCities.includes('专属业务员')"
          prop="businessAdminName"
          align="center"
          label="专属业务员"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('启用状态')"
          align="center"
          label="启用状态"
          width="80"
        >
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.audit != 0"
              :disabled="permissions.indexOf('system:admin:status') == -1"
              @change="statusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280px">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.audit == 0"
              size="mini"
              @click="consentClick(scope.row)"
              type="text"
              v-has="'community:poster:audit'"
              >审核通过</el-button
            >
            <el-button
              v-if="scope.row.audit == 0"
              size="mini"
              @click="refuseClick(scope.row)"
              type="text"
              v-has="'community:poster:audit'"
              >审核不通过</el-button
            >

            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'system:user:edit'"
              @click="editClick(scope.row)"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'system:user:userModule:info'"
              @click="changeClick(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-card class="footer" v-if="total > 0">
        <div>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[15, 30, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="500px"
      @open="editDialogOpen"
      class="editAccountDialog"
    >
      <div class="content">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef">
          <el-form-item prop="phone" label="手机号：">
            <div class="item">
              <el-input
                size="mini"
                @input="editForm.phone = editForm.phone.replace(/[^\?\d]/g, '')"
                v-model="editForm.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="companyName" label="企业名称：">
            <div class="item">
              <el-input
                size="mini"
                v-model="editForm.companyName"
                placeholder="请输入企业名称"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="name" label="姓名：">
            <div class="item">
              <el-input
                size="mini"
                v-model="editForm.name"
                placeholder="请输入邮箱"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="position" label="职位：">
            <div class="item">
              <el-input
                size="mini"
                v-model="editForm.position"
                placeholder="请输入职位"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="email" label="邮箱：">
            <div class="item">
              <el-input
                size="mini"
                v-model="editForm.email"
                placeholder="请输入邮箱"
              >
              </el-input>
            </div>
          </el-form-item>

          <el-form-item class="btns">
            <el-button size="mini" @click="editDialogVisible = false"
              >取 消</el-button
            >
            <el-button
              v-clickForbidden
              size="mini"
              type="primary"
              @click="editDialogSaveClick"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      checkedCities: [],
      cities: [
        "套餐",
        "有效期",
        "企业名称",
        "姓名",
        "手机号",
        "邮箱",
        "职位",
        "注册时间",
        "注册来源",
        "审核状态",
        "启用状态",
        "专属业务员",
      ],
      searchForm: {
        companyName: "",
        name: "",
        phone: "",
        audit: "",
        status: "",
        istrial: "",
        currentPlanId: "",
        businessAdminId: "",
      },
      auditOptions: [
        { label: "待审核", value: 0 },
        { label: "审核通过", value: 1 },
        { label: "审核拒绝", value: 2 },
      ],
      auditFormatter: {
        0: "待审核",
        1: "审核通过",
        2: "审核拒绝",
      },
      channelFormatter: {
        0: "",
        1: "pc",
        2: "小程序",
      },
      stautsFormatter: {
        0: "禁用",
        1: "启用",
      },
      stautsOptions: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
      istrialOptions: [
        { label: "是", value: 1 },
        { label: "否", value: 2 },
      ],
      tableLoading: false,
      tableHeight: 50,
      tableData: [],
      pageNum: 1,
      pageSize: 15,
      total: 0,
      editDialogVisible: false,
      editForm: {
        phone: "",
        companyName: "",
        name: "",
        email: "",
        position: "",
      },
      editRules: {
        companyName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
        ],
        phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
      },
      editId: "",
      salesmansList: [],
      plans: [],
    };
  },

  computed: {
    ...mapGetters(["permissions"]),
  },
  created() {
    this.getUserList();
    this.getSalesmans();
    this.getSetMeal();
    if (localStorage.checkedCities == undefined) {
      this.checkedCities = [
        "套餐",
        "有效期",
        "企业名称",
        "姓名",
        "手机号",
        "注册时间",
        "审核状态",
        "专属业务员",
      ];
    } else {
      this.checkedCities = localStorage.checkedCities.split(",");
    }
  },
  methods: {
    getSetMeal() {
      this.$api.getPlanModuleList().then((response) => {
        this.plans = JSON.parse(JSON.stringify(response.data.result.plans));
      });
    },
    getSalesmans() {
      this.$api.getSalesmans().then((res) => {
        if (res.data.code == "00000") {
          this.salesmansList = res.data.result;
        }
      });
    },
    changeClick(row) {
      this.$router.push({
        path: "/systemManagement/userManagementDetail",
        query: { id: row.id },
      });
    },
    saveCustom() {
      localStorage.checkedCities = this.checkedCities;
    },
    consentClick(row) {
      this.$confirm("审核通过，该用户将允许登录PC和小程序，确认吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            id: row.id,
            audit: 1,
          };
          this.$api.userAudit(data).then((res) => {
            if (res.data.code == "00000") {
              this.$message.success("审核通过成功");
              this.getUserList();
            }
          });
        })
        .catch(() => {});
    },
    refuseClick(row) {
      this.$confirm("审核不通过，该用户将不可登录PC和小程序，确认吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            id: row.id,
            audit: 2,
          };
          this.$api.userAudit(data).then((res) => {
            if (res.data.code == "00000") {
              this.$message.success("审核不通过成功");
              this.getUserList();
            }
          });
        })
        .catch(() => {});
    },
    searchClick() {
      this.pageNum = 1;
      this.getUserList();
    },
    resetClick() {
      this.$refs.searchFormRef.resetFields();
      this.pageNum = 1;
      this.getUserList();
    },

    /**
     * 获取用户列表
     * @param {*}
     */
    async getUserList() {
      this.tableLoading = true;
      await this.$api
        .userListTable({
          size: this.pageSize,
          page: this.pageNum,
          condition: {
            ...this.searchForm,
          },
        })
        .then((res) => {
          this.total = res.data.result.total;
          this.tableData = res.data.result.records;
          this.tableLoading = false;
        });
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row) {
      this.editForm = JSON.parse(JSON.stringify(row));
      this.editDialogVisible = true;
      this.editId = row.id;
    },
    /**
     * 状态更新回调
     * @param {*} row
     */
    async statusChange(row) {
      try {
        const flag = row.status; // 点击之后的值
        row.status = row.status === 1 ? 0 : 1; // switch点击前的状态
        const confirmTips = flag === 1 ? "启用" : "停用";
        const confirmTextTips = flag === 1 ? "允许" : "无法";
        //确认框
        const confirm = await this.$confirm(
          `${confirmTips}后，此账号${row.name}将${confirmTextTips}登录平台，确定${confirmTips}吗？`,
          "提示",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).catch(() => false);
        if (!confirm) return false;
        row.status = row.status === 1 ? 0 : 1;
        const res = await this.$api.userStatus({
          id: row.id,
          status: row.status,
        });
        if (res.data.code == "00000") {
          this.$message.success("状态更新成功");
        }
        this.getUserList();
      } catch (error) {
        this.$message.error(error);
      }
    },

    /**
     * 切换页面大小
     * @param {*} val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getUserList();
    },

    /**
     * 页码切换
     * @param {*} val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.getUserList();
    },

    /**
     * 打开新增和修改的回调
     * @param {*}
     */
    editDialogOpen() {
      if (this.$refs.editFormRef) this.$refs.editFormRef.resetFields();
    },

    /**
     * 编辑保存按钮
     * @param {*}
     */
    editDialogSaveClick() {
      this.$refs.editFormRef.validate(async (boolean) => {
        if (boolean) {
          let data = {
            id: this.editId,
            ...this.editForm,
          };

          const res = await this.$api.editStaff(data);
          if (res.data.code == "00000") {
            this.$message.success("修改成功");
            this.getUserList();
            this.editDialogVisible = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.accountList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .searchBox {
    .el-row {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        margin-bottom: 0;
      }
      .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        .nameSpan {
          padding-right: 10px;
          box-sizing: border-box;
          white-space: nowrap;
        }
        .el-input {
          width: 162px;
        }
      }
    }
  }
  .topBtn {
    margin: 10px 0;
    text-align: right;
  }

  .editAccountDialog {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409eff;
  background-color: #409eff;
}
/deep/.el-form-item {
  margin-bottom: 12px;
}
.custom-style {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}
</style>
